/*******************************************************************************
 *	                           bsp lib.c
 *******************************************************************************/
#include "bsp.h"
#include "lib_surport.h"
#include "os_obj.h"
#include "common.h"

extern uint32_t clks_per_us;

/*******************************************************************************
 * @brief  lib_tick_get
 * \param[in] none
 * \retval: tick
 *******************************************************************************/
uint16_t lib_tick_get(void)
{
	return app_tick_get();
}

/*******************************************************************************
 * @brief  lib_delay_0_5us
 * \param[in] u0_5us : 0.5us
 * \retval: none
 *******************************************************************************/
void lib_delay_0_5us(uint16_t u0_5us)
{
	NOP40();
	NOP40();
	NOP20();
}

/*******************************************************************************
 * @brief  lib_delay_us
 * \param[in] us
 * \retval: none
 *******************************************************************************/
void lib_delay_us(uint16_t us)
{
	uint32_t tCnt, tDelayCnt;
	uint32_t tStart;

	tStart = DWT->CYCCNT;
	tCnt = 0;
	tDelayCnt = us * clks_per_us - 10;

	while (tCnt < tDelayCnt)
	{
		bsp_dwt_check();
		tCnt = DWT->CYCCNT - tStart; // overflow is ok
	}
}

/*******************************************************************************
 * @brief  lib_delay_ms
 * \param[in] ms
 * \retval: none
 *******************************************************************************/
void lib_delay_ms(uint16_t ms)
{
	osDelay(ms_ticks(ms));
}

/*******************************************************************************
 * @brief  lib check
 * \param[in] none
 * \retval: none
 *******************************************************************************/
#define LRC_ADDR01 0x20000000
#define LRC_ADDR02 0x20000004
#define LRC_ADDR03 0x20000008
#define LRC_ADDR04 0x2000000C
#define LRC_ADDR0_RES 0x20000010
#define LRC_ADDR0_NRES 0x20000014
void lib_check_hook(int32_t st)
{
	uint32_t lrc;

	if (st > 2)
	{
		lrc = 0;
		lrc += inpw(LRC_ADDR01);
		lrc += inpw(LRC_ADDR02);
		lrc += inpw(LRC_ADDR03);
		lrc += inpw(LRC_ADDR04);

		outpw(LRC_ADDR0_RES, lrc);
		outpw(LRC_ADDR0_NRES, ~lrc);
	}
}

void lib_os_lock(void)
{
}

void lib_os_unlock(void)
{
}
